/**
 * 角色模块数据操作文件
 */

const { Op } = require('sequelize');
const { sequelize } = require('./common');
const { roles, users, role_menu } = sequelize.models;

/**
 * 添加角色
 * @param {*} model 
 * @returns 
 */
const add = model => roles.create(model);

/**
 * 修改角色
 * @param {*} model 
 * @returns 
 */
const update = model => sequelize.transaction(async t => {
    users.update({ role_name: model.name }, { where: { role_id: model.id }, transaction: t });
    return await roles.update(model, { where: { id: model.id }, transaction: t });
});

/**
 * 删除角色
 * @param {*} id 
 * @returns 
 */
const deleteRole = id => roles.destroy({ where: { id } });

/**
 * 获取所有角色
 * @returns 
 */
const getAll = () => roles.findAll();

/**
 * 是否存在相同的角色
 * @param {*} name 
 * @param {*} id 
 * @returns 
 */
const exists = (name, id = 0) => roles.findOne({
    where: {
        name,
        [Op.not]: {
            id
        }
    }
});

/**
 * 根据id获取数据
 * @param {*} id 
 * @returns 
 */
const getById = id => roles.findOne({ where: { id } });

/**
 * 权限设置
 * @param {*} role_id 
 * @param {*} menu_ids 
 */
const setRights = (role_id, menu_ids) => sequelize.transaction(async t => {
    await role_menu.destroy({ where: { role_id } }, { transaction: t });
    if (menu_ids.length) {
        await role_menu.bulkCreate(menu_ids.map(menu_id => ({
            role_id,
            menu_id
        })), { transaction: t });
    }
});

module.exports = {
    add,
    getAll,
    exists,
    update,
    getById,
    setRights,
    deleteRole
}